package qwfws

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"time"

	"gitee.com/gxcc/go-utils/utils"

	"gitee.com/gxcc/go-thirds/cache"
)

// QYWXProvider 企业微信服务商
type QYWXProvider struct {
	CorpId         string `json:"corpId"`
	ProviderSecret string `json:"providerSecret"`
}

func (w *QYWXProvider) reloadAccessToken() (string, error) {
	var reqUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/get_provider_token"
	var params = map[string]any{
		"corpid":          w.CorpId,
		"provider_secret": w.ProviderSecret,
	}
	data, _ := json.Marshal(params)

	res, err := utils.HttpPost(reqUrl, nil, data)
	if err != nil {
		slog.Error(err.Error())
		return "", err
	}

	type Info struct {
		Errcode             int    `json:"errcode"`
		Errmsg              string `json:"errmsg"`
		ProviderAccessToken string `json:"provider_access_token"`
		ExpiresIn           int    `json:"expires_in"`
	}
	var info Info
	if err := json.Unmarshal(res.Body, &info); err != nil {
		slog.Error(err.Error())
		return "", err
	}
	if len(info.ProviderAccessToken) == 0 {
		return "", errors.New("获取企业微信服务商accessToken失败，返回结果：" + string(res.Body))
	}

	// accessToken存放到redis中
	var ctx = context.Background()
	var accessTokenRedisKey = "qywx_provider_access_token_" + w.CorpId
	cache.RedisClient.Set(ctx, accessTokenRedisKey, info.ProviderAccessToken, time.Duration(info.ExpiresIn-60)*time.Second)

	slog.Debug("reloadAccessToken", "accessToken", info.ProviderAccessToken)
	return info.ProviderAccessToken, nil
}

// GetAccessToken 获取AccessToken
func (w *QYWXProvider) GetAccessToken() (string, error) {
	var ctx = context.Background()
	var accessTokenRedisKey = "qywx_provider_access_token_" + w.CorpId
	accessToken, err := cache.RedisClient.Get(ctx, accessTokenRedisKey).Result()
	if err != nil || len(accessToken) == 0 {
		return w.reloadAccessToken()
	}
	return accessToken, nil
}
